package controller

import (
	"agent-list---web-development/list/common"
	"agent-list---web-development/list/model"
	"agent-list---web-development/list/response"
	"agent-list---web-development/list/util"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func Register(c *gin.Context) {
	DB := common.DB
	username := c.PostForm("username")
	password := c.PostForm("password")
	if len(username) == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 423, nil, "用户名不能为空！")
		return
	}
	if len(username) > 50 {
		response.Response(c, http.StatusUnprocessableEntity, 423, nil, "用户名太长！")
		return
	}
	if len(password) == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 423, nil, "密码不能为空！")
		return
	}
	if len(password) < 6 || len(password) > 12 {
		response.Response(c, http.StatusUnprocessableEntity, 423, nil, "密码长度为6-12位！")
		return
	}
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 100, nil, "加密错误！")
		return
	}
	newUser := model.User{
		UserName: username,
		Account:  util.RandomString(DB),
		Password: string(hasedPassword),
		Avatar:   1,
	}
	err1 := DB.Create(&newUser).Error
	if err1 != nil {
		log.Println("err:", err1)
		response.Response(c, http.StatusBadRequest, 422, nil, "注册失败，请重试！")
		return
	}
	response.Success(c, gin.H{"user": newUser}, "注册成功！")
}
